﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using ASPNET.StarterKit.BusinessLogicLayer;
using ASPNET.StarterKit.DataAccessLayer;
using System.Data.SqlClient;

public partial class InventoryTracker_View : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGridView();
        }
        {

            string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
            SqlConnection con = new SqlConnection(constr);
            con.Open();
            String sql1 = "SELECT (InvoiceNumber) FROM Invoice";

            SqlCommand cmd1 = new SqlCommand(sql1, con);
            DataTable dataTable1 = GetDataTable(cmd1);
            //int InNO = int.Parse(dataTable1.Rows[0]["InvoiceNumber"].ToString());
            //InNO++;
            // txtInvNo.Text = InNO.ToString();
            txtInvNo.Text = dataTable1.Rows[0]["InvoiceNumber"].ToString();


            con.Close();

        }

        
        {
            txtDateTime.Text = System.DateTime.Now.ToString();
        }
    }


    

        
    private string GetConnectionString()
    {
        return System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
    }

    // Bind GridView
    private void BindGridView()
    {
        
        DataTable dt = new DataTable();
        SqlConnection connection = new SqlConnection(GetConnectionString());
        try
        {
            connection.Open();
            string sqlStatement = "SELECT * FROM InvoiceDetails";
            SqlCommand cmd = new SqlCommand(sqlStatement, connection);
            SqlDataAdapter sqlDa = new SqlDataAdapter(cmd);

            sqlDa.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                GridView1.DataSource = dt;
                GridView1.DataBind();
            }
        }
        catch (System.Data.SqlClient.SqlException ex)
        {
            string msg = "Fetch Error:";
            msg += ex.Message;
            throw new Exception(msg);
        }
        finally
        {
            connection.Close();
        }
    }
    

    // Insert New or Update Record
    private void UpdateOrAddNewRecord( int No, string InvoiceItem, string ItemDescription, float InvoiceItemRate , int InvoiceItemQty, float InvoiceTotalAmount, bool isUpdate)
    {
        //String SelectValue = DdlInvNum.SelectedValue;

        SqlConnection connection = new SqlConnection(GetConnectionString());
        string sqlStatement = string.Empty;

        if (!isUpdate)
        {
            sqlStatement = "INSERT INTO InvoiceDetails ( InvoiceNumber,InvoiceItem,ItemDescription,InvoiceItemRate,InvoiceItemQty,InvoiceTotalAmount) VALUES (@InvoiceNumber, @InvoiceItem,@ItemDescription,@InvoiceItemRate,@InvoiceItemQty,@InvoiceTotalAmount)";
        }
        else
        {
            sqlStatement = "UPDATE InvoiceDetails SET InvoiceItemRate= @InvoiceItemRate,InvoiceItemQty = @InvoiceItemQty,InvoiceTotalAmount = @InvoiceTotalAmount WHERE [InvoiceNumber]=@InvoiceNumber";
        }
        try
        {
            connection.Open();
            SqlCommand cmd = new SqlCommand(sqlStatement, connection);
            cmd.Parameters.AddWithValue("@InvoiceNumber", No);
            cmd.Parameters.AddWithValue("@InvoiceItem", InvoiceItem);
            cmd.Parameters.AddWithValue("@ItemDescription", ItemDescription);
            cmd.Parameters.AddWithValue("@InvoiceItemRate", InvoiceItemRate);
            cmd.Parameters.AddWithValue("@InvoiceItemQty", InvoiceItemQty);
            cmd.Parameters.AddWithValue("@InvoiceTotalAmount", InvoiceTotalAmount);
            //cmd.Parameters.AddWithValue("@ItemCode", ItemCode);

            cmd.CommandType = CommandType.Text;
            cmd.ExecuteNonQuery();
        }
        catch (System.Data.SqlClient.SqlException ex)
        {
            string msg = "Insert/Update Error:";
            msg += ex.Message;
            throw new Exception(msg);

        }
        finally
        {
            connection.Close();
        }
    }
    
    protected void btnAddNew_Click(object sender, EventArgs e)
    {
        UpdateOrAddNewRecord(int.Parse( txtInvNo.Text), DdlItName.SelectedItem.ToString(),txtDes.Text, float.Parse( txtRate.Text),int.Parse( txtQty.Text),float.Parse( txtTotAmt.Text), false);
        //Re Bind GridView to reflect changes made
        BindGridView();

        txtRate.Text = "";
        txtQty.Text = "";
        txtTotAmt.Text = "";
        txtDes.Text = "";
    
    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex; // turn to edit mode
        BindGridView(); // Rebind GridView to show the data in edit mode

    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1; //swicth back to default mode
        BindGridView(); // Rebind GridView to show the data in default mode
    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {//Accessing Edited values from the GridView
        int Num =int.Parse( GridView1.Rows[e.RowIndex].Cells[0].Text.ToString()); 
        string InvoiceItem = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text.ToString(); 
        string ItemDescription = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text.ToString(); 
        float InvoiceItemRate = float.Parse(((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text.ToString()); 
        int InvoiceItemQty = int.Parse(((TextBox)GridView1.Rows[e.RowIndex].Cells[4].Controls[0]).Text.ToString()); 
        float InvoiceTotalAmount = float.Parse (((TextBox)GridView1.Rows[e.RowIndex].Cells[5].Controls[0]).Text.ToString());
        

        UpdateOrAddNewRecord(Num,InvoiceItem, ItemDescription, InvoiceItemRate, InvoiceItemQty, InvoiceTotalAmount, true); 
        GridView1.EditIndex = -1;
        BindGridView(); // Rebind GridView to reflect changes made

    }


    private void DeleteRecord(int No)
    {
        SqlConnection connection = new SqlConnection(GetConnectionString());
        string sqlStatement = "DELETE FROM InvoiceDetails WHERE InvoiceNumber = @InvoiceNumber";
        try
        {
            connection.Open();
            SqlCommand cmd = new SqlCommand(sqlStatement, connection);
            cmd.Parameters.AddWithValue("@InvoiceNumber", No);
            cmd.CommandType = CommandType.Text;
            cmd.ExecuteNonQuery();
        }
        catch (System.Data.SqlClient.SqlException ex)
        {
            string msg = "Deletion Error:";
            msg += ex.Message;
            throw new Exception(msg);

        }
        finally
        {
            connection.Close();
        }
    }
    
    protected void txtTotAmt_TextChanged(object sender, EventArgs e)
    {
        //int TA = int.Parse(txtTotAmt.Text);
        float R =float.Parse(txtRate.Text);
        int Q = int.Parse(txtQty.Text);

        float TAmt = R * Q;
        txtTotAmt.Text = TAmt.ToString();
    }

    protected void GridView1_RowDeleting1(object sender, GridViewDeleteEventArgs e)
    {
        int Num = int.Parse(GridView1.Rows[e.RowIndex].Cells[0].Text);
        DeleteRecord(Num);//call delete method
        BindGridView();//rebind grid to reflect changes made
    }
    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {

    }
    protected void DdlItName_SelectedIndexChanged(object sender, EventArgs e)
    {
        String SelectValue = DdlItName.SelectedValue;

        string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
        SqlConnection con = new SqlConnection(constr);
        con.Open();
        String sql2 = "SELECT * FROM  MaterialMaster WHERE  [ItemCode]=" + SelectValue;
        SqlCommand cmd2 = new SqlCommand(sql2, con);
        DataTable dataTable2 = GetDataTable(cmd2);
        txtDes.Text= dataTable2.Rows[0]["ItemDescription"].ToString();
        txtRate.Text = dataTable2.Rows[0]["SellingRate"].ToString();

       // String sql3 = "SELECT * FROM  InvoiceDetails WHERE  [ItemCode]=" + SelectValue;
        //SqlCommand cmd3 = new SqlCommand(sql3, con);
        //DataTable dataTable3 = GetDataTable(cmd3);
        //lblAvail.Text = " <b> Available: </b>" + dataTable3.Rows[0]["InvoiceItemQty"].ToString();

        con.Close();

        txtQty.Text = "";
        txtTotAmt.Text = "";
    }

    
    protected void DdlCustoInfo_SelectedIndexChanged(object sender, EventArgs e)
    {
int x = DdlCustoInfo.SelectedIndex;
string CustInfo = DdlCustoInfo.SelectedValue;

        string constr= ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
        SqlConnection con = new SqlConnection(constr);
        con.Open();
        String sql = "SELECT [CustName], [CustAddr1], [CustAddr2], [CustAddr3], [CustCity], [CustState], [CustStatus],[CustFax], [CustMobile], [CustPhone], [CustCountry], [CustEmail], [CustZipCode] FROM [CustomerMaster] WHERE  [CustID]=" + CustInfo ;
        SqlCommand cmd = new SqlCommand(sql, con);

        DataTable dataTable = GetDataTable(cmd);
        string val = dataTable.Rows[0]["CustName"].ToString() + "<br>" + dataTable.Rows[0]["CustAddr1"].ToString();

       

       if (!String.IsNullOrEmpty( dataTable.Rows[0]["CustAddr2"].ToString()) )
       {
            val = val + "<br>" + dataTable.Rows[0]["CustAddr2"].ToString();
       }
      // val = dataTable.Rows[0]["CustName"].ToString() + "<br>" + dataTable.Rows[0]["CustAddr1"].ToString() + "<br>" + dataTable.Rows[0]["CustAddr2"].ToString();
       if (!String.IsNullOrEmpty(dataTable.Rows[0]["CustAddr3"].ToString()))
       {
           val = val + "<br>" + dataTable.Rows[0]["CustAddr3"].ToString();
       }
       val = val + dataTable.Rows[0]["CustCity"].ToString() + "-" + dataTable.Rows[0]["CustZipCode"].ToString() + "<br>" + dataTable.Rows[0]["CustState"].ToString() + "<br>" + dataTable.Rows[0]["CustCountry"].ToString();
       if (!String.IsNullOrEmpty(dataTable.Rows[0]["CustMobile"].ToString()))
       {
           val = val + "<br> <b> Mobile: </b>" + dataTable.Rows[0]["CustMobile"].ToString();
       }
       if (!String.IsNullOrEmpty(dataTable.Rows[0]["CustPhone"].ToString()))
       {
           val = val + "<br> <b> Ph:</b>" + dataTable.Rows[0]["CustPhone"].ToString();
       }
       if (!String.IsNullOrEmpty(dataTable.Rows[0]["CustFax"].ToString()))
       {
           val = val + "<br> <b> Fax:</b>" + dataTable.Rows[0]["CustFax"].ToString();
       }
       
       if (!String.IsNullOrEmpty(dataTable.Rows[0]["CustEmail"].ToString()))
       {
           val = val + "<br> <b>E-Mail:</b>" + dataTable.Rows[0]["CustEmail"].ToString();
       }
       //val = val + "<br>" + dataTable.Rows[0]["CustPhone"].ToString() + "<br>" + dataTable.Rows[0]["CustFax"].ToString() + "<br>" + dataTable.Rows[0]["CustMobile"].ToString() + "<br>" + dataTable.Rows[0]["CustEmail"].ToString();
       int r = dataTable.Rows.Count;
       CustLabel.Text = val;

       
        // string val1 = "Name:" + "<br>" + "Address 1:" + "<br>" + " Address 2:" + "<br>" + "Address 3:" + "<br>" + "City:"+"<br>"+"State:"+"<br>"+"Country:"+"<br>"+"Phone No:"+"<br>"+"Mobile No:"+"<br>"+"Fax:"+"<br>"+"E-Mail Id:"+"<br>"+"ZipCode:";
      // CustInfLabel.Text = val1;
        con.Close();

    }


    public static DataTable GetDataTable(SqlCommand cmd)
    {

        SqlDataAdapter da = new SqlDataAdapter();
        //set the SelectCommand of the adapter
        da.SelectCommand = cmd;
        // create a new DataTable
        DataTable dtGet = new DataTable();
        //fill the DataTable
        da.Fill(dtGet);
        //return the DataTable
        return dtGet;

    }



    protected void btnAddCust_Click(object sender, EventArgs e)
    {
        Response.Redirect("CustomerMaster.aspx");
    }


    

    protected void TaxTextBox_TextChanged(object sender, EventArgs e)
    {



    }
    protected void DDRTax_SelectedIndexChanged(object sender, EventArgs e)
    {
        int x =int.Parse( txtInvNo.Text);
        string InvoiceNumber = txtInvNo.Text;

        string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
        SqlConnection con = new SqlConnection(constr);
        con.Open();

        String sql4 = "SELECT (InvoiceTotalAmount) FROM [InvoiceDetails] WHERE ([InvoiceNumber] = " + InvoiceNumber + ")";
        //String sql4 = "SELECT SUM(InvoiceItemRate) AS Expr1 FROM [InvoiceDetails] WHERE ([InvoiceNumber] = " + InvoiceNumber + ")";
        SqlCommand cmd4 = new SqlCommand(sql4, con);

        DataTable dataTable4 = GetDataTable(cmd4);
        object Sum = dataTable4.Compute("sum(InvoiceTotalAmount)", "");
        string sumVal = Sum.ToString();

        con.Close();


        if (DiscountTextBox.Text == null || DiscountTextBox.Text == "")
        {

            DiscountTextBox.Text = "0";

        }

        Double su = Double.Parse(sumVal);
        Double d = Double.Parse(DiscountTextBox.Text);
        su = su - (su * (d / 100));

        GrandTotalTextBox.Text = su.ToString();

        Double TA = su;
        Double tax = Double.Parse(DDRTax.SelectedItem.Value);
        Double r = (tax / 100);
        TA = TA + (TA * r);
        TaxTextBox.Text = TA.ToString("N2");
        GrandTotalTextBox.Text = TA.ToString("N2");


    }

    protected void txtPlace_TextChanged(object sender, EventArgs e)
    {


    }
    protected void GrandTotalTextBox_TextChanged(object sender, EventArgs e)
    {



    }
    protected void txtDateTime_TextChanged(object sender, EventArgs e)
    {

    }
    protected void DiscountTextBox_TextChanged(object sender, EventArgs e)
    {

    }




    protected void btnSubmit_Click(object sender, EventArgs e)
    {

        DataAccess DA = DataAccessHelper.GetDataAccess();
        InvoiceDetails aInvoice = new InvoiceDetails(DdlItName.SelectedValue,txtDes.Text,float.Parse( txtRate.Text),DDRTax.SelectedValue,float.Parse( txtTotAmt.Text),DateTime.Parse( txtDateTime.Text),int.Parse( txtQty.Text),float.Parse( DiscountTextBox.Text),float.Parse( GrandTotalTextBox.Text),
            DdlItName.SelectedIndex);
        try
        {
            if (DA.CreateInvoiceDetails(aInvoice))
            {
                lblResult.Text = "Success";
            }
            else
            {
                lblResult.Text = "Failure";
            }
        }
        catch (Exception ex)
        {
            lblResult.Text = ex.Message.ToString();
        }



        Invoice aInv = new Invoice( DdlCustoInfo.SelectedIndex,int.Parse( txtPlace.Text), DDRTax.SelectedIndex);
        try
        {
            if (DA.CreateInvoice(aInv))
            {
                lblResult.Text = "Success";
            }
            else
            {
                lblResult.Text = "Failure";
            }
        }
        catch (Exception ex)
        {
            lblResult.Text = ex.Message.ToString();
        }

    }
}

    
